package org.xnsg.app.controller;

import com.alibaba.fastjson.JSON;
import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.Easy;
import com.eova.common.utils.EncryptUtil;
import com.eova.common.utils.xx;
import com.eova.model.*;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.eova.widget.WidgetManager;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtomImp;
import com.jfinal.plugin.activerecord.Record;
import org.xnsg.app.controller.utils.ControllerHelper;
import org.xnsg.app.core.bean.Result;

import java.sql.SQLException;
import java.util.*;

/**
 * @author zhaopan
 * @date :2017/4/17
 * @Description:用户管理重写
 */
public class UserController extends Controller /*SingleController*/
{
    protected MetaObjectIntercept intercept = null;
    final Controller ctrl = this;
    private String errorInfo = "";

    private final Record record = new Record();

    /*
    @Override
    public void list() {
        String menuCode = this.getPara(0);
        Menu menu = Menu.dao.findByCode(menuCode);
        MenuConfig config = menu.getConfig();
        String objectCode = config.getObjectCode();
        MetaObject object = MetaObject.dao.getByCode(objectCode);
        List fields = MetaField.dao.queryByObjectCode(objectCode);
        User user = (User)this.getSessionAttr("user");
        List btnList = Button.dao.queryByMenuCode(menuCode, user.getInt("rid").intValue());
        Map resultMap =new HashMap();
        resultMap.put("isQuery", Boolean.valueOf(MetaObject.dao.isExistQuery(objectCode)));
        resultMap.put("menu", menu);
        resultMap.put("btnList", btnList);
        resultMap.put("object", object);
        resultMap.put("fields", fields);
        this.renderJson(new Result(resultMap));
    }
    */

    public void add() throws Exception
    {
        String objectCode = this.getPara(0);
        MetaObject object = sm.meta.getMeta(objectCode);
        Iterator var4 = object.getFields().iterator();
        while (var4.hasNext())
        {
            MetaField ac = (MetaField) var4.next();
            ac.put("is_disable", Boolean.valueOf(false));
        }
        WidgetManager.buildRef(this, object);
        this.intercept = (MetaObjectIntercept) TemplateUtil.initIntercept(object.getBizIntercept());
        if (this.intercept != null)
        {
            AopContext ac1 = new AopContext(this, object);
            this.intercept.addInit(ac1);
        }
        Map resultMap = new HashMap();
        //resultMap.put("object", object);
        resultMap.put("fields", object.getFields());
        resultMap.put("dtype", ControllerHelper.comboJson(null, "c_pt_user", "dtype", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("post", ControllerHelper.comboJson(null, "c_pt_user", "post", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("rid", ControllerHelper.comboJson(null, "c_pt_user", "rid", new Object[]{this.getSessionAttr("user")}));

        this.renderJson(new Result(resultMap));
    }

    public void detail()
    {
        String objectCode = getPara(0);
        String userId = getPara("userId");
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        String pkValue = String.valueOf(user.getInt("id"));
        MetaObject object = this.buildData(false, objectCode, pkValue);
        Map resultMap = new HashMap();
        //resultMap.put("object", object);

        //this.buildWidget(resultMap);
        //部门类别
        List<Record> dtypes = ControllerHelper.comboJson(null, "c_pt_user", "dtype", new Object[]{this.getSessionAttr("user")});
        Map<String, String> dtypeMap = new HashMap<String, String>();
        for (Record record : dtypes)
        {
            dtypeMap.put(record.getStr("id"), record.getStr("cn"));
        }
        //职位
        List<Record> posts = ControllerHelper.comboJson(null, "c_pt_user", "post", new Object[]{this.getSessionAttr("user")});
        Map<String, String> postMap = new HashMap<String, String>();
        for (Record record : posts)
        {
            postMap.put(record.getStr("id"), record.getStr("cn"));
        }
        //角色
        List<Record> rids = ControllerHelper.comboJson(null, "c_pt_user", "rid", new Object[]{this.getSessionAttr("user")});
        Map<String, String> ridMap = new HashMap<String, String>();
        for (Record record : rids)
        {
            ridMap.put(String.valueOf(record.get("id")), record.getStr("cn"));
        }

        //证件类型
        List<Record> zjtypes = ControllerHelper.comboJson(null, "c_pt_user", "zjtype", new Object[]{this.getSessionAttr("user")});
        Map<String, String> zjtypeMap = new HashMap<String, String>();
        for (Record record : zjtypes)
        {
            zjtypeMap.put(String.valueOf(record.get("id")), record.getStr("cn"));
        }
        //性别
        List<Record> xbs = ControllerHelper.comboJson(null, "c_pt_user", "xb", new Object[]{this.getSessionAttr("user")});
        Map<String, String> xbMap = new HashMap<String, String>();
        for (Record record : xbs)
        {
            xbMap.put(String.valueOf(record.get("id")), record.getStr("cn"));
        }
        //状态
        List<Record> pstatuss = ControllerHelper.comboJson(null, "c_pt_user", "pstatus", new Object[]{this.getSessionAttr("user")});
        Map<String, String> pstatusMap = new HashMap<String, String>();
        for (Record record : pstatuss)
        {
            pstatusMap.put(String.valueOf(record.get("id")), record.getStr("cn"));
        }
        //所属行政区
        String xid = ControllerHelper.findCnByEn("c_pt_user", "xid", ((User) this.getSessionAttr("user")).getStr("xid"), new Object[]{this.getSessionAttr("user")});

        for (MetaField field : object.getFields())
        {
            if ("dtype".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), dtypeMap.get(String.valueOf(field.get("value"))));
            } else if ("post".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), postMap.get(String.valueOf(field.get("value"))));
            } else if ("rid".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), ridMap.get(String.valueOf(field.get("value"))));
            } else if ("zjtype".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), zjtypeMap.get(String.valueOf(field.get("value"))));
            } else if ("xb".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), xbMap.get(String.valueOf(field.get("value"))));
            } else if ("pstatus".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), pstatusMap.get(String.valueOf(field.get("value"))));
            } else
            {
                resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            }
        }
        List<Map> list = JSON.parseArray((String) JSON.parseObject(xid, Map.class).get("data"), Map.class);
        resultMap.put("xid", (String) (list.get(0).get("aname")));
        this.removeSessionAttr("user");
        this.renderJson(resultMap);
    }

    /**
     * 修改密码
     */
    public void updatePwd()
    {
        String oldPwd = getPara("oldPwd");
        String newPwd = getPara("newPwd");
        String userId = getPara("userId");
        User user = User.dao.getByLoginId(getPara("userId"));
        if (xx.isOneEmpty(oldPwd, newPwd))
        {
            renderJson(new Easy("密码都不能为空"));
            return;
        }
        // 当前用户
        String pwd = user.getStr("login_pwd");
        // 旧密码是否正确
        if (!pwd.equals(EncryptUtil.getSM32(oldPwd)))
        {
            renderJson(new Easy("密码错误"));
            return;
        }

        // 修改密码
        user.set("login_pwd", EncryptUtil.getSM32(newPwd)).update();

        renderJson(new Easy());
    }

    public void update() throws Exception
    {
        String objectCode = getPara(0);
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        String pkValue = String.valueOf(user.getInt("id"));

        MetaObject object = this.buildData(true, objectCode, pkValue);

        this.intercept = (MetaObjectIntercept) TemplateUtil.initIntercept(object.getBizIntercept());
        if (this.intercept != null)
        {
            AopContext ac = new AopContext(this, object);
            this.intercept.updateInit(ac);
        }
        Map resultMap = new HashMap();
        //resultMap.put("object", object);
        //resultMap.put("fields", object.getFields());
        //this.buildWidget(resultMap);
        //resultMap.put("dtype", ControllerHelper.comboJson(null, "c_pt_user", "dtype", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("post_List", ControllerHelper.comboJson(null, "c_pt_user", "post", new Object[]{user}));
//        Map<String, String> xbMap = new HashMap<String, String>();
//        for (Record record : rids){
//            xbMap.put(String.valueOf(record.get("id")),record.getStr("cn"));
//        }

        //resultMap.put("rid", ControllerHelper.comboJson(null, "c_pt_user", "rid", new Object[]{this.getSessionAttr("user")}));
        resultMap.put("zjtype_List", ControllerHelper.comboJson(null, "c_pt_user", "zjtype", new Object[]{user}));
        resultMap.put("xb_List", ControllerHelper.comboJson(null, "c_pt_user", "xb", new Object[]{user}));
        resultMap.put("pstatus_List", ControllerHelper.comboJson(null, "c_pt_user", "pstatus", new Object[]{user}));
        //resultMap.put("xid", ControllerHelper.findCnByEn("c_pt_user", "xid", ((User) this.getSessionAttr("user")).getStr("xid"), new Object[]{this.getSessionAttr("user")}));
        for (MetaField field : object.getFields()){
            resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            resultMap.put(field.getStr("en")+"_qx", (boolean)field.get("is_update"));
        }

        this.removeSessionAttr("user");
        this.renderJson(new Result(resultMap));

    }

    public MetaObject buildData(boolean isEdit, String objectCode, String pkValue)
    {
        MetaObject object = sm.meta.getMeta(objectCode);
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        MetaField ei;
        Object value;
        for (Iterator var7 = object.getFields().iterator(); var7.hasNext(); ei.put("value", value))
        {
            ei = (MetaField) var7.next();
            String key = ei.getEn();
            value = record.get(key);
            if (value == null)
            {
                value = "";
            }

//            if (!isEdit) {
//                ei.set("is_disable", Boolean.valueOf(true));
//            }
        }

        //WidgetManager.buildRef(this, object);

        return object;
    }

    public void doUpdate()
    {
        String objectCode = this.getPara(0);
        final MetaObject object = sm.meta.getMeta(objectCode);
        final Map reMap = WidgetManager.buildData(this, object.getFields(), this.record, object.getPk(), false);
        Object pkValue = this.record.get(object.getPk());
        this.intercept = (MetaObjectIntercept) TemplateUtil.initIntercept(object.getBizIntercept());
        boolean flag = Db.tx(new IAtomImp(object, reMap)
        {
            public boolean run() throws SQLException
            {
                try
                {
                    AopContext e = new AopContext(UserController.this.ctrl, UserController.this.record);
                    String msg;
                    if (UserController.this.intercept != null)
                    {
                        msg = UserController.this.intercept.updateBefore(e);
                        if (!xx.isEmpty(msg))
                        {
                            UserController.this.errorInfo = msg;
                            return false;
                        }
                    }

                    if (!xx.isEmpty(this.object.getTable()))
                    {
                        System.out.println(JsonKit.toJson(UserController.this.record));
                        Db.use(this.object.getDs()).update(this.object.getTable(), this.object.getPk(), UserController.this.record);
                    } else
                    {
                        WidgetManager.operateView(this.object.getPk(), this.reMap, "update");
                    }

                    if (UserController.this.intercept != null)
                    {
                        msg = UserController.this.intercept.updateAfter(e);
                        if (!xx.isEmpty(msg))
                        {
                            UserController.this.errorInfo = msg;
                        }
                    }

                    return true;
                } catch (Exception var3)
                {
                    UserController.this.errorInfo = TemplateUtil.buildException(var3);
                    return false;
                }
            }
        });
        if (!flag)
        {
            this.renderJson(new Easy(this.errorInfo));
        } else if (!flag)
        {
            this.renderJson(new Easy("修改失败" + this.errorInfo));
        } else
        {
            EovaLog.dao.info(this, 2, object.getStr("code") + "[" + pkValue + "]");
            if (this.intercept != null)
            {
                try
                {
                    ArrayList e = new ArrayList();
                    e.add(this.record);
                    AopContext ac = new AopContext(this, e);
                    String msg = this.intercept.updateSucceed(ac);
                    if (!xx.isEmpty(msg))
                    {
                        this.errorInfo = msg;
                    }
                } catch (Exception var9)
                {
                    this.errorInfo = TemplateUtil.buildException(var9);
                    this.renderJson(new Easy("修改成功,updateSucceed拦截执行异常!" + this.errorInfo));
                    return;
                }
            }

            this.renderJson(new Easy());
        }
    }

    private void buildWidget(Map map)
    {
        List widgets = Widget.dao.findByType(2);
        map.put("widgets", widgets);
    }
}
